package com.sleepcamel.resteasyConfigurator.util;

import java.io.File;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

public class FileUtils {

	public static File getDirectoryToSave(Shell shell, String message) {
		return getDirectoryToSave(shell, message, (String)null);
	}
	
	public static File getDirectoryToSave(Shell shell, String message, File initialPath) {
		if ( initialPath != null )
			return getDirectoryToSave(shell, message, initialPath.getAbsolutePath());
		
		return getDirectoryToSave(shell, message);
	}
	
	public static File getDirectoryToSave(Shell shell, String message, String initialPath) {
    	File dirFile = null;
		DirectoryDialog directoryDialog = new DirectoryDialog(shell);
        
        directoryDialog.setMessage(message);
        
        if ( initialPath != null ){
        	directoryDialog.setFilterPath(initialPath);
        }
        
        String dirPath = directoryDialog.open();
        if(dirPath != null) {
        	dirFile = new File(dirPath);
        	dirFile.mkdirs();
        }
        return dirFile;
	}
	
	public static File getFileToSave(Shell shell) {
		FileDialog saveDialog = new FileDialog(shell, SWT.SAVE);
	    saveDialog.setFilterExtensions(new String[] { "*.rec;", "*.*" });
	    saveDialog.setFilterNames(new String[] { "Rest Easy Configurations (*.rec)",
	        "All Files " });

	    saveDialog.open();
	    String name = saveDialog.getFileName();

	    if (name.equals(""))
	      return null;

	    if (name.indexOf(".rec") != name.length() - 4) {
	      name += ".rec";
	    }

	    File file = new File(saveDialog.getFilterPath(), name);
	    if (file.exists()) {
	      MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES
	          | SWT.NO);
	      box.setText("Project exists");
	      box.setMessage("File " + file.getName()
	          + " already exists. Do you wish to overwrite?");
	      if (box.open() != SWT.YES) {
	        return null;
	      }
	    }
	    return file;
	}

	public static File getFileToLoad(Shell shell) {
		FileDialog loadDialog = new FileDialog(shell, SWT.OPEN);
	    loadDialog.setFilterExtensions(new String[] { "*.rec;", "*.*" });
	    loadDialog.setFilterNames(new String[] { "Rest Easy Configurations (*.rec)",
	        "All Files " });

	    loadDialog.open();
	    String name = loadDialog.getFileName();

	    if (name.equals(""))
	      return null;

	    File file = new File(loadDialog.getFilterPath(), name);
	    if (!file.exists() || !file.isFile()) {
	    	return null;
	    }
	    return file;
	}
}
